import { login as loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
// 导入router
import router from '@/router'
// 导入完整路由
import { constantRoutes, asyncRoutes, allRouter } from '@/router/routes'

// 过滤方法
// asyncroutes: 传递过来的动态路由
// roleName: 用户信息返回的权限
const filterRoutesHandler = (asyncRoutes, userInfoRoutes) => {
  let router = asyncRoutes.filter((item) => {
    if (item.children && item.children.length) {
      filterRoutesHandler(item.children, userInfoRoutes)
    }
    // console.log(item)
    let routeName = userInfoRoutes.includes(item.name)
    return routeName
  })
  return router
}

const addRoute = (routes) => {
  routes.map((item) => {
    // console.log(router)
    router.addRoutes(item)
  })
}
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',

    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [] // 本用户的角色赋予的新增的动态路由
  }
}

const state = getDefaultState()

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.data.name // 用户名
    state.avatar = userInfo.data.avatar // 头像
    state.roles = userInfo.data.roles // 角色列表
    state.buttons = userInfo.data.buttons // 按钮权限列表
    state.routes = userInfo.arbitrarilyRoutes // 侧边栏展示
  },

  SET_TOKEN(state, token) {
    state.token = token
  },

  RESET_USER(state) {
    Object.assign(state, getDefaultState())
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginAPI
        .login(username, password)
        .then((result) => {
          console.log(result)
          const { data } = result
          commit('SET_TOKEN', data.token)
          setToken(result.data.token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const { data } = await loginAPI.getInfo()

    // 获取对应的用户信息的时候从中取出对应的权限
    const fliterRoutes = filterRoutesHandler(asyncRoutes, data.routes)
    // console.log(fliterRoutes)
    const arbitrarilyRoutes = fliterRoutes.concat(constantRoutes, allRouter)
    // console.log(arbitrarilyRoutes)
    router.addRoutes(arbitrarilyRoutes)
    commit('SET_USER', { data, arbitrarilyRoutes })
  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    // 如果当前是登陆的, 请求退出登陆
    if (state.name) {
      await loginAPI.logout()
    }
    // 提交重置用户信息的mutation
    commit('RESET_USER')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
